package com.huluobo.day11_im.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.huluobo.day11_im.R;
import com.huluobo.day11_im.adapter.MyFragmentAdapter;
import com.huluobo.day11_im.addFriend.view.AddFriendActivity;
import com.huluobo.day11_im.addGroup.view.AddGroupActivity;
import com.huluobo.day11_im.contact.view.MyContactFragment;
import com.huluobo.day11_im.fragment.ContactFragment;
import com.huluobo.day11_im.fragment.ConversationFragment;
import com.huluobo.day11_im.fragment.MineFragment;
import com.huluobo.day11_im.fragment.MyConversationFragment;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private BottomNavigationView bottomNavigationView;
    private List<Fragment> fragmentList;
    private MyFragmentAdapter fragmentAdapter;

    private TextView title;
    private ImageView add;
    private View badge;
    private TextView count;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        viewPager = findViewById(R.id.main_vp);
        bottomNavigationView = findViewById(R.id.main_nav);
        title = findViewById(R.id.main_title);
        add = findViewById(R.id.main_add);

        fragmentList = new ArrayList<>();
        fragmentList.add(new ConversationFragment());
//        fragmentList.add(new ContactFragment());
//        fragmentList.add(new MyConversationFragment());
        fragmentList.add(new ContactFragment());
        fragmentList.add(new MineFragment());

        fragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(fragmentAdapter);

        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO}, 102);
        add.setVisibility(View.VISIBLE);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {

            }

            @SuppressLint("NonConstantResourceId")
            @Override
            public void onPageSelected(int position) {
                MenuItem item = bottomNavigationView.getMenu().getItem(position);
                switch (item.getItemId()) {
                    case R.id
                            .tab_conversation:
                        title.setText("微信");
                        add.setVisibility(View.VISIBLE);
                        break;

                    case R.id
                            .tab_contact:
                        title.setText("联系人");
                        add.setVisibility(View.VISIBLE);
                        break;
                    case R.id
                            .tab_mine:
                        title.setText("我的");
                        add.setVisibility(View.GONE);
                    default:
                        break;
                }
                item.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id
                            .tab_conversation:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id
                            .tab_contact:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id
                            .tab_mine:
                        viewPager.setCurrentItem(2);
                    default:
                        break;
                }
                return true;
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //popupMenu
                PopupMenu popupMenu = new PopupMenu(MainActivity.this, add);
                popupMenu.inflate(R.menu.add_menu);
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @SuppressLint("NonConstantResourceId")
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id
                                    .addFriend:
                                Intent intent = new Intent(MainActivity.this,
                                        AddFriendActivity.class);
                                startActivity(intent);
                                break;
                            case R.id
                                    .addGroup:
                                Intent intentAddGroup = new Intent(MainActivity.this,
                                        AddGroupActivity.class);
                                startActivity(intentAddGroup);
                                break;
                            case R.id
                                    .addScan:
                                toScan();
                                break;
                            case R.id
                                    .addPay:
                                Toast.makeText(MainActivity.this, "展示付款码", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                break;
                        }
                        return true;
                    }
                });
                popupMenu.show();
            }
        });

        //1.首先拿到menuView,也就是在底部导航栏添加的menu
        BottomNavigationMenuView menuView =
                (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
        //2.通过menu才能拿到第一个itemView,也就是需要标记角标的位置
        BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(0);
        //3.在通过itemView去添加一个角标
        badge = LayoutInflater.from(this).inflate(R.layout.view_badge, itemView, false);
        itemView.addView(badge);
        count = badge.findViewById(R.id.badge_tv);
        count.setText(EMClient.getInstance().chatManager().getUnreadMessageCount() + "");

        EMClient.getInstance().chatManager().addMessageListener(new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        badge.setVisibility(View.VISIBLE);
                        count.setText(EMClient.getInstance().chatManager().getUnreadMessageCount() + "");
                    }
                });
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (EMClient.getInstance().chatManager().getUnreadMessageCount() == 0) {
            badge.setVisibility(View.GONE);
        } else {
            badge.setVisibility(View.VISIBLE);
            count.setText(EMClient.getInstance().chatManager().getUnreadMessageCount() + "");
        }
    }

    private void toScan() {
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            String username = data.getExtras().get(CodeUtils.RESULT_STRING).toString();
            try {
                EMClient.getInstance().contactManager().addContact(username, null);
                Toast.makeText(this, "添加好友成功", Toast.LENGTH_SHORT).show();
            } catch (HyphenateException e) {
                Toast.makeText(this, "添加还有失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                throw new RuntimeException(e);
            }
        }
    }
}